﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ALinq.Mapping;

namespace ALinq.BBS.DataAccess
{
    partial class User
    {
        private Posts posts;
        private Posts favorPosts;
        partial void OnCreated()
        {
            CreationDate = DateTime.Now;
        }

        public static User CreateInstance(int id)
        {
            var db = new Database();
            var user = db.Users.SingleOrDefault(o => o.ID == id);

            return user;
        }

        public static User CreateInstance(string name)
        {
            var db = new Database();
            var user = db.Users.SingleOrDefault(o => o.Name == name);

            return user;
        }

        public void Update()
        {
            DataContext.SubmitChanges();
        }

        public Posts Posts
        {
            get
            {
                if (posts == null)
                {
                    posts = new Posts(this);
                }
                return posts;
            }
        }

        public Posts FavorPosts
        {
            get
            {
                if (favorPosts == null)
                {
                    var db = this.DataContext;
                    var q = from a in db.PostFavors
                            join b in db.Posts on a.PostID equals b.ID
                            into c
                            from d in c.DefaultIfEmpty()
                            select d;

                    favorPosts = new Posts(q, db, FavorPostCount);
                }

                return favorPosts;
            }
        }

    }


}
